package org.jeecg.modules.operations.assistant.xcbd.service.impl;

import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.operations.assistant.wechat.service.QuickStart;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdCollectionRecord;
import org.jeecg.modules.operations.assistant.xcbd.entity.XcbdSalesContract;
import org.jeecg.modules.operations.assistant.xcbd.entity.YearCountInfo;
import org.jeecg.modules.operations.assistant.xcbd.mapper.XcbdCollectionRecordMapper;
import org.jeecg.modules.operations.assistant.xcbd.mapper.XcbdSalesContractMapper;
import org.jeecg.modules.operations.assistant.xcbd.service.IXcbdCollectionRecordService;
import org.jeecg.modules.operations.assistant.xcbd.service.OrderNumberGenerator;
import org.jeecg.modules.operations.assistant.xcbd.service.QRCodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import static org.jeecg.modules.operations.assistant.wechat.service.QuickStart.scanCodePay;

/**
 * @Description: 收款记录
 * @Author: jeecg-boot
 * @Date:   2024-12-21
 * @Version: V1.0
 */
@Service
@Slf4j
public class XcbdCollectionRecordServiceImpl extends ServiceImpl<XcbdCollectionRecordMapper, XcbdCollectionRecord> implements IXcbdCollectionRecordService {
	
	@Autowired
	private XcbdCollectionRecordMapper xcbdCollectionRecordMapper;
	@Autowired
	private XcbdSalesContractMapper xcbdSalesContractMapper;
	
	@Override
	public List<XcbdCollectionRecord> selectByMainId(String mainId) {
		return xcbdCollectionRecordMapper.selectByMainId(mainId);
	}
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveCollectionRecord(XcbdCollectionRecord collectionRecord) {
		XcbdSalesContract xcbdSalesContract = xcbdSalesContractMapper.selectById(collectionRecord.getSalesContractId());
		BigDecimal amountCollected = collectionRecord.getAmountCollected();
		BigDecimal collectionAmount = xcbdSalesContract.getCollectionAmount();
		String paymentType2="";
		if (collectionAmount.compareTo(amountCollected) >= 0) {
			String orderNumber = OrderNumberGenerator.generateOrderNumber();
			String codeUrl = "";
			if(collectionRecord.getPaymentMethod().equals("2")){ //微信支付
				// 使用微信扫描 code_url 对应的二维码，即可体验Native支付
				String paymentType= collectionRecord.getPaymentType();

				if(paymentType.equals("0")){  //定金
					paymentType2="定金";
				} else if(paymentType.equals("1")){  //尾款
					paymentType2="尾款";
				}else {  // 2 全款
					paymentType2="全款";
				}
				String content = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23bf3224159631e6&redirect_uri=https%3A%2F%2Fshxt.gzxcbd.cn%2Fjeecgboot%2Fwxpay%2Fpay&response_type=code&scope=snsapi_base&state="+orderNumber+"#wechat_redirect";
				String filePath = "/QRCode/"+orderNumber+".png";
				log.info(uploadpath+filePath);
				generateAndSaveQRCode(content, uploadpath+filePath);
				collectionRecord.setScanCodePayUrl(filePath);
//				codeUrl = QuickStart.scanCodePay(amountCollected.intValue(),xcbdSalesContract.getCustomerName()+"支付合同"+paymentType2,"https://shxt.gzxcbd.cn",orderNumber);
			}
//			collectionAmount = collectionAmount.subtract(amountCollected);
//			xcbdSalesContract.setCollectionAmount(collectionAmount); // 待回款金额
			xcbdSalesContractMapper.updateById(xcbdSalesContract);
			collectionRecord.setId(null);
			collectionRecord.setOrderNumber(orderNumber);
			xcbdCollectionRecordMapper.insert(collectionRecord);
		} else {
			throw new JeecgBootException("操作失败，收款金额大于待回款金额！");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateReceiptStatus(XcbdCollectionRecord collectionRecord) {
		XcbdSalesContract xcbdSalesContract = xcbdSalesContractMapper.selectById(collectionRecord.getSalesContractId());
		BigDecimal amountCollected = collectionRecord.getAmountCollected();
		BigDecimal collectionAmount = xcbdSalesContract.getCollectionAmount();
		String processProgress ="暂未到账";
		if(collectionRecord.getReceiptStatus().equals("1")){
			processProgress = "确认到账";
			collectionAmount = collectionAmount.subtract(amountCollected);
			xcbdSalesContract.setCollectionAmount(collectionAmount); // 待回款金额
			xcbdSalesContractMapper.updateById(xcbdSalesContract);
		} else if(collectionRecord.getReceiptStatus().equals("2")) {
			processProgress = "取消支付";
		}else {
			processProgress ="暂未到账";
		}
		//获取登录用户信息
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		collectionRecord.setProcessProgress(loginUser.getRealname()+"审批"+processProgress);
		collectionRecord.setProcessStatus("财务已审批");
		xcbdCollectionRecordMapper.updateById(collectionRecord);
	}

	@Override
	public List<YearCountInfo> getYearCountInfo() {
		return xcbdCollectionRecordMapper.selectYearCountInfo();
	}

	@Override
	public List<YearCountInfo> getMonthCountInfo() {
		return xcbdCollectionRecordMapper.selectMonthCountInfo();
	}

	@Override
	public List<YearCountInfo> getWeekCountInfo() {
		return xcbdCollectionRecordMapper.selectWeekCountInfo();
	}

	private void generateAndSaveQRCode(String content, String filePath) {
		try {
			QRCodeService.generateQRCode(content, filePath);
			// 保存二维码文件路径到数据库
			// saveQRCodePathToDatabase(filePath);
		} catch (WriterException | IOException e) {
			e.printStackTrace();
			// 处理异常
		}
	}
}
